package com.yunding.redis.impl;


import com.yunding.redis.RedisManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author 杜奕明
 * @date 2019/10/1
 */
@Component
public class RedisManagerImpl implements RedisManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        //序列化为String
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        //序列化为Json
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        redisTemplate.setKeySerializer(stringSerializer);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setHashKeySerializer(stringSerializer);

        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        this.redisTemplate = redisTemplate;

    }


    @Override
    public void put(String key, Object value, long seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }


    /**
     * 默认存1天
     *
     */
    @Override
    public void put(String key, Object value) {
        put(key, value, 86400);
    }


    @Override
    public void putWithoutSeconds(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }


    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    @Override
    public boolean delete(String key) {
        return redisTemplate.delete(key);
    }
}
